package com.shijunhao.graduation.utils;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shijunhao.graduation.annotations.WrapperCondition;
import com.shijunhao.graduation.enums.SqlSymbol;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: shijunhao
 * @date: 2022/3/5 17:29
 * @description:
 */
public class WrapperUtils {
    public static <T> Wrapper<T> query(Object obj){
        Class<?> clazz = obj.getClass();
        QueryWrapper<T> wrapper = new QueryWrapper<>();

        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
            WrapperCondition condition = field.getAnnotation(WrapperCondition.class);
            if(condition != null){
                SqlSymbol sqlSymbol = condition.condition();
                String name = camel4underline(field.getName());
                Object value;
                try {
                    value = field.get(obj);
                    if(value != null)
                        sqlSymbol.getBinding().bindingCondition(wrapper,name,value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return wrapper;
    }

    public static String camel4underline(String param){
        Pattern p= Pattern.compile("[A-Z]");
        if(param==null ||param.equals("")){
            return "";
        }
        StringBuilder builder=new StringBuilder(param);
        Matcher mc=p.matcher(param);
        int i=0;
        while(mc.find()){
            builder.replace(mc.start()+i, mc.end()+i, "_"+mc.group().toLowerCase());
            i++;
        }

        if('_' == builder.charAt(0)){
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }
}
